package com.jse;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import com.jse.server.HttpExchange;
import com.jse.server.HttpHandler;
import com.jse.server.HttpServer;
import com.jse.web.Action;
import com.jse.web.Web;

public interface Server {
	void start()throws Exception;

	public static void await() throws Exception{
		if(Jse.runing)return;
		String type=Jse.conf.getString("server.type");
		if("tomcat".equals(type)){
			tomcat.start();
		}else if("jetty".equals(type)){
			jetty.start();
		}else{
			jdkserver.start();
		}
	}
	
	Server tomcat=()->{Js.execute(Io.read(Server.class.getResourceAsStream("/META-INF/jse/tomcat.js")));};
	Server jetty=()->{Js.execute(Io.read(Server.class.getResourceAsStream("/META-INF/jse/jetty.js")));};
	Server jdkserver=()->{
		HttpServer server = HttpServer.create(new InetSocketAddress(80), 0);
		server.createContext("/",new HttpHandler() {
			
			@Override
			public void handle(HttpExchange ex) throws IOException {
				Action.service(ex);
				Web.filter(ex,false);//执行后置处理
			}
		});
//        server.createContext("/ws/",new Action());
	    server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
	    server.start();
	    Web.init();
	};
	
}
